<?php

namespace app\service;

use app\models\Card;
use app\models\Incr;
use app\models\MemberCards;
use BaseComponents\base\ErrorCode;
use BaseComponents\base\Exception;

class CardService
{

    /**
     * 报名抽奖
     * @param $cardNum
     * @return bool
     * @throws Exception
     */
    public function apply($cardNum)
    {
        if (!$this->lotterySwitch()) {
            throw new Exception(ErrorCode::ERR_1006);
        }

        if (!MemberCards::exists($cardNum)) {
            throw new Exception(ErrorCode::ERR_1003);
        }

        if (!Card::exists($cardNum)) {
            Card::add($cardNum);

            Incr::memberApplyStat();

            return true;
        } else {
            throw new Exception(ErrorCode::ERR_1007);
        }
    }

    /**
     * 获取直播开关
     * @return bool
     */
    public function liveSwitch()
    {
        /** @var \Redis $redis */
        $redis = \Yii::$app->get('redis');

        return !!$redis->get('liveSwitch');
    }

    /**
     * 抽奖开机
     * @return bool
     */
    private function lotterySwitch()
    {
        /** @var \Redis $redis */
        $redis = \Yii::$app->get('redis');

        return !!$redis->get('lotterySwitch');
    }

}